// pkg/ublk/downloader.go

package ublk

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"time"
)

// Downloader 块下载器
type Downloader struct {
	client *http.Client
}

// NewDownloader 创建下载器
func NewDownloader() *Downloader {
	return &Downloader{
		client: &http.Client{
			Timeout: 30 * time.Minute,
		},
	}
}

// DownloadRange 下载指定范围
func (d *Downloader) DownloadRange(ctx context.Context, url string, offset, size int64) ([]byte, error) {
	req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
	if err != nil {
		return nil, err
	}

	// 设置 HTTP Range 请求头
	req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+size-1))

	resp, err := d.client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("http request failed: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusPartialContent && resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("http status %d", resp.StatusCode)
	}

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("read response failed: %w", err)
	}

	return data, nil
}
